package com.simple.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simple.common.enumdto.BankType;
import com.simple.common.PageResult;
import com.simple.dto.BankDTO;
import com.simple.dto.BankTypeDTO;
import com.simple.mapper.BankMapper;
import com.simple.pojo.Bank;
import com.simple.service.BankService;
import com.simple.utils.BeanConverterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName BankServiceImpl
 * @Author SimpleTree
 **/
@Service
public class BankServiceImpl implements BankService {
    @Resource
    private BankMapper bankMapper;
    @Autowired
    private BeanConverterUtil beanConverterUtil;

    @Override
    public PageResult getBanks(BankDTO bankDTO) {
        PageHelper.startPage(bankDTO.getPageNum(), bankDTO.getPageSize(),"create_time desc");

        Example example = new Example(Bank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", bankDTO.getUserId());
        if (bankDTO.getStartTime() != null) {
            criteria.andGreaterThan("createTime", bankDTO.getStartTime());
        }
        if (bankDTO.getEndTime() != null) {
            criteria.andLessThan("createTime", bankDTO.getEndTime());
        }
        List<Bank> banks = bankMapper.selectByExample(example);

        PageInfo<Bank> pageInfo = new PageInfo<>(banks);
        return new PageResult(pageInfo.getTotal(),pageInfo.getPageNum(),beanConverterUtil.toBankDTO(banks));
    }

    @Override
    public List<BankTypeDTO> getBankTypes() {
        return Arrays.stream(BankType.values()).map(bankType -> new BankTypeDTO(bankType.getCode(), bankType.getMsg())).collect(Collectors.toList());
    }

    @Override
    public void saveBank(BankDTO BankDTO) {
        Bank bank = beanConverterUtil.toBank(BankDTO);
        bank.setCreateTime(new Date());
        bank.setUpdateTime(new Date());
        bankMapper.insert(bank);
    }

    @Override
    public void updateBank(BankDTO BankDTO) {
        bankMapper.updateByPrimaryKeySelective(beanConverterUtil.toBank(BankDTO));
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        bankMapper.deleteByIds(ids);
    }
}
